package org.gl.training.planner.dao;

import java.util.List;

import org.gl.training.planner.model.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository(value = "userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	@Autowired
	public void init(SessionFactory factory) {
		setSessionFactory(factory);
	}

	@SuppressWarnings("unchecked")
	public User getUser(String username) {
		if (username == null) {
			return null;
		}

		List<User> userList = getHibernateTemplate().find(
				"from User u join fetch u.userTypesList where u.userName=?",
				username);

		if (userList.size() == 1) {
			return userList.get(0);
		}

		return null;
	}

	public void save(User user) {
		getHibernateTemplate().merge(user);
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		List<User> userList = getHibernateTemplate().find(
				"from User u join fetch u.userTypesList");
		return userList;
	}

	@Override
	public void delete(User user) {
		getHibernateTemplate().delete(user);

	}

	@Override
	public User find(Integer id) {
		return getHibernateTemplate().get(User.class, id);
	}
}
